<?php
require_once 'config21.php';
if (!isset($_SESSION['userid'])) {
    header('Location: login21.php');
    exit;
}

// 添加课程
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['add_course'])) {
    $course_name = $_POST['course_name'];
    $teacher_id = $_POST['teacher_id'];
    $credit = $_POST['credit'];
    
    $sql = "INSERT INTO courses (course_name, teacher_id, credit) 
            VALUES ('$course_name', '$teacher_id', '$credit')";
    
    if ($conn->query($sql) === TRUE) {
        header('Location: course_management21.php');
        exit;
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
?>

<!DOCTYPE html>
<html lang="zh-Hans">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加课程</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .add-button {
            display: inline-block;
            background-color: #007bff;
            color: white;
            padding: 8px 16px;
            text-decoration: none;
            border-radius: 4px;
        }
        .add-button:hover {
            background-color: #0056d3;
        }
        form {
            max-width: 500px;
            margin: 20px auto;
        }
        label {
            display: inline-block;
            width: 100px;
            margin-bottom: 10px;
        }
        input[type="text"],
        input[type="number"],
        select {
            width: 200px;
            padding: 5px;
            margin-bottom: 10px;
        }
        input[type="submit"] {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <h2>添加课程</h2>
    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
        <label for="course_name">课程名称：</label>
        <input type="text" name="course_name" required><br>

        <label for="teacher_id">授课教师：</label>
        <select name="teacher_id" required>
            <option value="">请选择教师</option>
            <?php
            $teacher_sql = "SELECT * FROM teachers";
            $teacher_result = $conn->query($teacher_sql);
            while ($teacher_row = $teacher_result->fetch_assoc()) {
                echo "<option value='" . $teacher_row['teacher_id'] . "'>" . $teacher_row['teacher_name'] . "</option>";
            }
            ?>
        </select><br>

        <label for="credit">学分：</label>
        <input type="number" name="credit" step="0.5" min="0.5" max="10" required><br>

        <input type="submit" value="添加" name="add_course">
    </form>
    <div align="right"><a href="course_management21.php" class="add-button">返回</a></div>
</body>
</html>